package com.scs.application.modules.upms.excel.handler;

import cn.afterturn.easypoi.handler.impl.ExcelDataHandlerDefaultImpl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.scs.application.core.utils.Reflections;
import com.scs.application.core.utils.SpringHolder;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.upms.entity.Office;
import com.scs.application.modules.upms.service.OfficeService;

import java.util.List;
import java.util.Map;

/**
 */
public class OfficeDataHandler extends ExcelDataHandlerDefaultImpl {

    private Map<String,Office> codeMap = Maps.newHashMap();

    public OfficeDataHandler() {
        List<Office> offices = getOfficeService().list(Wrappers.<Office>query().select("id,code"));
        for (Office office : offices) {
            codeMap.put(office.getCode(), office);
        }

    }

    @Override
    public String[] getNeedHandlerFields() {
        return new String[]{"机构代码"};
    }

    @Override
    public Object importHandler(Object obj, String name, Object value) {

        if (!"机构代码".equalsIgnoreCase(name)) {
            return null;
        }
        if (value == null || StringUtils.isBlank(value.toString())) {
            return null;
        }
        Office office = codeMap.get(value.toString());
        if(office != null && Reflections.getAccessibleField(obj,"officeId") != null){
            Reflections.setFieldValue(obj,"officeId",office.getId());
        }

        return null;
    }


    public OfficeService getOfficeService() {
        return SpringHolder.getBean(OfficeService.class);
    }

}
